// pages/buy/index.js
import Config from '../../etc/config'
var app = getApp()
const {
  $Toast
} = require('../../components/dist/base/index');
// 当联想词数量较多，使列表高度超过340rpx，那设置style的height属性为340rpx，小于340rpx的不设置height，由联想词列表自身填充
// 结合上面wxml的<scroll-view>
var arrayHeight = 0;

Page({

  /**
   * 页面的初始数据
   */
  data: {
    checkTags: [],
    right: '../../images/icon/right.png',
    imgDefault:'../../images/icon/no-img.png',
    bindSource: [], //绑定到页面的数据，根据用户输入动态变化
    inputValue: '', //点击结果项之后替换到文本框的值
    hideScroll: false,
    label: [],
    addId: '',
    disabled: false,
    buy: true,
    type: '',
    hidden: false,
    num: 1
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function(options) {
    this.data.typeId = options.typeId
    this.data.type = options.type
    if (wx.getStorageSync('userId')) {
      this.getAdImg(options.type)
    } else {
      wx.navigateTo({
        url: '../authorize/index',
      })
    }
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function(options) {
    this.setLabelChecked(this.data.checkTags, this.data.label)
    if (this.data.addId !== '') {
      this.getAddrById()
    }
    this.getAddLength()
    if (wx.getStorageSync('userId')) {
      if (this.data.addId == ''){
        this.getAdImg(this.data.type)
      }
    } else {
      wx.navigateTo({
        url: '../authorize/index',
      })
    }
  },

  // 获取用户地址数量
  getAddLength() {
    let params = {
      userId: wx.getStorageSync('userId'),
    }
    let token = wx.getStorageSync("token");
    Config._post('/useraddress/userAddressIsExistByUserId', token, params).then(res => {
      if (res.data) {
        this.setData({
          msg: '选择收货地址',
          handleWay: 'selectAddress'
        })
      } else {
        this.setData({
          msg: '增加收货地址',
          handleWay: 'addAddress'
        })
      }
    })
  },

  // 获取默认地址和页面广告图
  getAdImg(type) {
    let params = {
      userId: wx.getStorageSync('userId'),
      typeId: type
    }
    let token = wx.getStorageSync("token");
    Config._post('/merServicesType/getImgStrByTypeId', token, params).then(res => {
      console.log(res)
      if (res.data.userAddress) {
        this.setData({
          addressInfo: res.data.userAddress,
          addId: res.data.userAddress.id
        })
        this.getShop()
      }
      if (res.data.path) {
        this.setData({
          img: res.data.path
        })
      }
    })
  },

  // 选择地址
  selectAddress() {
    wx.navigateTo({
      url: '../address/index?typeId=' + this.data.typeId,
      success(){
      }
    })
    this.setData({
      shopName: ''
    })
  },

  // 添加地址
  addAddress() {
    wx.navigateTo({
      url: '../add-address/index',
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  // 修改地址
  editAddess(e) {
    wx.navigateTo({
      url: '../add-address/index?id=' + e.currentTarget.dataset.id,
      success: function(res) {},
      fail: function(res) {},
      complete: function(res) {},
    })
  },

  // 根据地址ID获取地址详情
  getAddrById() {
    let params = {
      id: this.data.addId
    }
    let token = wx.getStorageSync("token");
    Config._post('/useraddress/getAddrById', token, params).then(res => {
      let data = res.data
      this.setData({
        addressInfo: data
      })
      this.getShop()
    })
  },

  // 修改会员卡号
  cardChange(e) {
    var cardNumber = 'addressInfo.member'
    this.setData({
      cardNumber: e.detail.value
    })
  },

  // 获取门店信息
  getShop() {
    let params = {
      merSerTypeId: this.data.typeId,
      addressId: this.data.addId
    }
    let token = wx.getStorageSync("token");
    Config._post('/merServicesType/getMerSerTypeDetail', token, params).then(res => {
      if (res.code === 0) {
        if (res.data.label) {
          this.setData({
            label: res.data.label,
            buy: false
          })
        }
        this.setData({
          shopId: res.data.shopId,
          shopName: res.data.shopName
        })
        wx.setNavigationBarTitle({
          title: res.data.name
        })
      }
    })
  },

  // 跳转全部推荐标签
  goLabels() {
    if (this.data.shopId) {
      let checkTags = JSON.stringify(this.data.checkTags);
      wx.navigateTo({
        url: '../labels/index?shopId=' + this.data.shopId + '&checkTags=' + checkTags,
      })
    } else {
      if (this.data.addId == '') {
        $Toast({
          content: '请选择联系人'
        })
      } else {
        $Toast({
          content: '未找到商家'
        })
      }
      return
    }
  },

  // 点击推荐标签
  tagClick(e) {
    this.setData({
      hidden: true
    })
    let params = {
      labelId: e.currentTarget.dataset.id
    }
    let token = wx.getStorageSync("token");
    Config._post('/label/getLabelById', token, params).then(res => {
      this.setData({
        detail: res.label
      })
    })
    // let option = {
    //   id: e.currentTarget.dataset.id,
    //   name: e.currentTarget.dataset.name
    // }
    // var checkTags = this.data.checkTags
    // for (let i = 0; i < this.data.checkTags.length; i++) {
    //   if (e.currentTarget.dataset.id === this.data.checkTags[i].id) {
    //     checkTags.splice(i, 1)
    //     for (let j = 0; j < this.data.label.length; j++) {
    //       if (e.currentTarget.dataset.id == this.data.label[j].labelId) {
    //         this.data.label[j].checked = false
    //       }
    //     }
    //     this.setData({
    //       checkTags: checkTags,
    //       label: this.data.label
    //     })
    //     return false
    //   }
    // }
    // checkTags.push(option)
    // this.setData({
    //   checkTags: checkTags
    // })
    // this.setLabelChecked(checkTags, this.data.label)
  },

  subtractNum(e) {
    this.data.num = this.data.num - 1 < 0 ? 0 : this.data.num - 1
    this.setData({
      num: this.data.num
    })
  },
  addNum(e) {
    this.data.num = this.data.num + 1 > 99 ? 99 : this.data.num + 1
    this.setData({
      num: this.data.num
    })
  },

  inputNum(e) {
    this.setData({
      num: Number(e.detail.value)
    })
  },

  confirm(){
    if (this.data.inputValue){
      this.data.inputValue += ',' + this.data.detail.labelName + ':' + this.data.num
    }else{
      this.data.inputValue += this.data.detail.labelName + ':' + this.data.num
    }
    this.setData({
      num: 1,
      hidden: false,
      inputValue: this.data.inputValue,
      // 当用户选择某个联想词，隐藏下拉列表
      hideScroll: true,
      bindSource: [],
    })
  },
  cancel(){
    this.setData({
      num: 1,
      hidden: false
    })
  },

  // 给未进行点击事件的标签改变选中状态
  setLabelChecked(sourceList, desList) {
    for (let i = 0; i < sourceList.length; i++) {
      for (let j = 0; j < desList.length; j++) {
        if (sourceList[i].id == desList[j].labelId) {
          desList[j].checked = true
        }
      }
    }
    this.setData({
      label: desList
    })
  },

  // 删除选定标签
  tagClickDel(e) {
    var checkTags = this.data.checkTags
    for (let i = 0; i < this.data.checkTags.length; i++) {
      if (e.currentTarget.dataset.id === this.data.checkTags[i].id) {
        checkTags.splice(i, 1)
        break
      }
    }
    this.setData({
      checkTags: checkTags
    })
    for (let j = 0; j < this.data.label.length; j++) {
      if (e.currentTarget.dataset.id == this.data.label[j].labelId) {
        this.data.label[j].checked = false
      }
    }
    this.setData({
      label: this.data.label
    })
  },

  // 选定标签的备注
  valueChange(e) {
    let idx = e.target.dataset.index,
      value = e.detail.value
    var index = "checkTags[" + idx + "].value"
    this.setData({
      [index]: value
    })
  },

  // 输入框联想功能
  valueInput(e) {
    //用户实时输入值
    var prefix = e.detail.value
    //匹配的结果
    var newSource = []
    if (prefix != "") {
      let params = {
        label: prefix,
        shopId: this.data.shopId
      }
      let token = wx.getStorageSync("token");
      Config._post('/merServicesType/labelAssociate', token, params).then(res => {
        if (res.code == 0) {
          let adapterSource = res.data
          if (adapterSource && adapterSource.length > 0) {
            adapterSource.forEach(function(e) {
              // 用户输入的字符串如果在数组中某个元素中出现，将该元素存到newSource中
              if (e.labelName.indexOf(prefix) != -1) {
                newSource.push(e)
              }
            })
          }

        }

        // 如果匹配结果存在，那么将其返回，相反则返回空数组
        if (newSource.length != 0) {
          this.setData({
            // 匹配结果存在，显示自动联想词下拉列表
            hideScroll: false,
            bindSource: newSource,
            arrayHeight: newSource.length * 71,
          })
        } else {
          this.setData({
            // 匹配无结果，不现实下拉列表
            hideScroll: true,
            bindSource: [],
            inputValue: e.detail.value
          })
        }
      })
    } else {
      this.setData({
        bindSource: []
      })
    }
  },

  // 用户点击选择某个联想字符串时，获取该联想词，并清空提醒联想词数组
  itemtap: function(e) {
    let option = {
      id: e.target.dataset.item.labelId,
      name: e.target.dataset.item.labelName
    }
    var checkTags = this.data.checkTags
    for (let i = 0; i < this.data.checkTags.length; i++) {
      if (e.target.dataset.id === this.data.checkTags[i].id) {
        return false
      }
    }
    checkTags.push(option)
    this.setData({
      checkTags: checkTags
    })

    this.setData({
      // .id在wxml中被赋值为{{item}}，即当前遍历的元素值
      inputValue: e.target.id,
      // 当用户选择某个联想词，隐藏下拉列表
      hideScroll: true,
      bindSource: [],
    })

    this.setData({
      hidden: false
    })
    let params = {
      labelId: e.target.dataset.item.labelId
    }
    let token = wx.getStorageSync("token");
    Config._post('/label/getLabelById', token, params).then(res => {
      this.setData({
        detail: res.label,
      })
    })
  },

  // 下单
  orderSubmit: function(e) {
    this.setData({
      disabled: true
    })
    let formId = e.detail.formId
    var buyerRemake = ''
    // let data = this.data.checkTags
    // if (this.data.checkTags) {
    //   for (let i = 0; i < this.data.checkTags.length; i++) {
    //     if (!data[i].value) {
    //       data[i].value = ''
    //     }
    //     if (i === data.length - 1) {
    //       buyerRemake += data[i].name + data[i].value
    //     } else {
    //       buyerRemake += data[i].name + data[i].value + ';'
    //     }
    //   }
    // }
    // if (this.data.value) {
    //   buyerRemake += this.data.value
    // }
    if (!this.data.inputValue) {
      $Toast({
        content: '请选择或填写购买商品'
      });
      this.setData({
        disabled: false
      })
      wx.hideLoading()
      return
    }
    let params = {
      userId: wx.getStorageSync('userId'),
      merTypeId: this.data.typeId,
      buyerRemake: this.data.inputValue,
      orderCardNumber: this.data.addressInfo.member,
      shopId: this.data.shopId,
      addressId: this.data.addId,
      formId: formId,
    }
    let token = wx.getStorageSync("token");
    Config._post('/order/submitOrder', token, params).then(res => {
      
      this.setData({
        disabled: false
      })
      wx.reLaunch({
        url: '../success-msg/index',
      })
    })
  },

  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function() {

  },


  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function() {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function() {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function() {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function() {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function() {
    return {
      // title: wx.getStorageSync('mallName') + '——' + app.globalData.shareProfile,
      title: app.globalData.shareTitle,
      path: '/pages/buy/index?type=' + this.data.type + '&typeId=' + this.data.typeId,
      imageUrl: app.globalData.shareImg,
      success: function(res) {
        // 转发成功
      },
      fail: function(res) {
        // 转发失败
      }
    }
  },
})